package com.orange.cetback.controller.user;

import com.orange.cetback.common.constant.JwtClaimsConstant;
import com.orange.cetback.common.context.BaseContext;
import com.orange.cetback.common.properties.JwtProperties;
import com.orange.cetback.common.utils.AliOssUtil;
import com.orange.cetback.common.utils.JwtUtil;
import com.orange.cetback.common.vo.Result;
import com.orange.cetback.pojo.dto.UserLoginDTO;
import com.orange.cetback.pojo.entity.User;
import com.orange.cetback.pojo.vo.UserLoginVO;
import com.orange.cetback.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author chenenjun
 * @since 2025-02-11
 */
@Slf4j
@RestController
@RequestMapping("/userApi/user")
@Tag(name = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AliOssUtil aliOssUtil;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}",userLoginDTO.getCode());
        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .studyLevel(user.getStudyLevel())
                .build();
        return Result.success(userLoginVO);
    }

    @Operation(summary = "切换学习等级")
    @PutMapping("/switchLevel")
    public Result<String> switchLevel(@RequestParam String studyLevel){
        log.info("切换学习等级：{}",studyLevel);
        userService.switchLevel(studyLevel);
        return Result.success("切换成功");
    }
    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    public Result<List<User>> getUserList(){
        List<User> users = userService.getUserList();
        return Result.success(users);
    }

    @Operation(summary = "上传用户头像")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        try {
            // 生成唯一文件名（防止覆盖）
            String originalFilename = file.getOriginalFilename();
            String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 调用OSS工具上传
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(url);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
        }
        return Result.fail("文件上传失败");
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo(){
        User user = userService.getById(BaseContext.getCurrentId());
        return Result.success(user);
    }

    @Operation(summary = "修改用户信息")
    @PutMapping("/update")
    public Result<String> updateUserInfo(@RequestBody User user){
        log.info("修改用户信息：{}",user);
        userService.updateById(user);
        return Result.success("修改成功");
    }
}
